package cn.com.shinho.hg.gate.filter;

import cn.com.shinho.hg.core.base.response.ResponseData;
import cn.com.shinho.hg.core.common.exception.CoreExceptionEnum;
import cn.com.shinho.hg.core.common.exception.ServiceException;
import cn.com.shinho.hg.core.constant.Constant;
import cn.com.shinho.hg.gate.config.properties.JwtProperties;
import cn.com.shinho.hg.gate.constants.ZuulConstants;
import cn.com.shinho.hg.gate.consumer.AuthServiceConsumer;
import com.netflix.zuul.ExecutionStatus;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.ZuulFilterResult;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * 请求路径权限过滤器
 *
 * @author Mr.Ye
 * @Date 2018-11-14-上午10:43
 */
public class PathMatchFilter extends ZuulFilter {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AuthServiceConsumer authServiceConsumer;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return ZuulConstants.PATH_MATCH_FILTER;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        if (request.getServletPath().equals(jwtProperties.getAuthPath())) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public Object run() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();

        Object userId = currentContext.get(Constant.IDENTITY_HEADER);

        if (userId == null) {
            return  new ZuulFilterResult(CoreExceptionEnum.PERMISSION_ERROR, ExecutionStatus.FAILED);
//            throw new ServiceException(CoreExceptionEnum.PERMISSION_ERROR);
        }
        ResponseData permissionUrls = authServiceConsumer.getUserPermissionUrls(Long.valueOf(userId.toString()));

        if(permissionUrls.getCode()!=HttpStatus.OK.value()){
            throw new ServiceException(CoreExceptionEnum.PERMISSION_ERROR);
        }
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean hasPermission = false;
        for (String permission : (Set<String>)permissionUrls.getObject()) {
            hasPermission = antPathMatcher.match(permission, request.getServletPath());
            if (hasPermission) {
                break;
            }
        }

        if (hasPermission) {
            return null;
        } else {
           return  new ZuulFilterResult(CoreExceptionEnum.PERMISSION_ERROR, ExecutionStatus.FAILED);
//            throw new ServiceException(CoreExceptionEnum.PERMISSION_ERROR);
        }
    }
}
